import time
from PySide.QtGui import QTextCursor
import urllib
import urlparse
import sys

LIB_VERSION = '0.1'
GUI_CONF_VERSION = '0.1b'
DB_URL = 'mongodb://localhost:27017/'
DB_NAME = 'mads-dev3-db'

HEADERS = {'User-Agent' : 'Custom-user-agent'}

END_FLAG = False

def logt(messageInput,start_time,appender=None):
        message = messageInput.encode('utf8')
        if(appender):
            appender.append(message + ' in '+ str(time.time() - start_time) + " seconds")
        else:
            print message + ' in '+ str(time.time() - start_time) + " seconds"
        
def log(messageInput,appender=None):
    try:
        message = messageInput.encode('utf8')
        if(appender):
            appender.append(message)
            print '['+str(message)+']'
        else:
            print str(message)
    except UnicodeEncodeError:
        print "Unicode problem in logging"
    except:
        print "Unexpected error in logging", sys.exec_info()[0]

def url_fix(s, charset='utf-8'):
    """Sometimes you get an URL by a user that just isn't a real
    URL because it contains unsafe characters like ' ' and so on.  This
    function can fix some of the problems in a similar way browsers
    handle data entered by the user:



    :param charset: The target charset for the URL if the url was
                    given as unicode string.
    """
    if isinstance(s, unicode):
        s = s.encode(charset, 'ignore')
    scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
    path = urllib.quote(path, '/%')
    qs = urllib.quote_plus(qs, ':&=')
    return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))

class OutLog:
    def __init__(self, edit, out=None, color=None):
        """(edit, out=None, color=None) -> can write stdout, stderr to a
        QTextEdit.
        edit = QTextEdit
        out = alternate stream ( can be the original sys.stdout )
        color = alternate color (i.e. color stderr a different color)
        """
        self.edit = edit
        self.out = None
        self.color = color

    def write(self, m):
        if self.color:
            tc = self.edit.textColor()
            self.edit.setTextColor(self.color)

        self.edit.moveCursor(QTextCursor.End)
        self.edit.insertPlainText( m )

        if self.color:
            self.edit.setTextColor(tc)

        if self.out:
            self.out.write(m)